package com.vcredit.creditcat.service.product.h5;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.vcredit.creditcat.service.product.util.RSAUtils;
import com.vcredit.creditcat.util.Base64Utils;
import com.vcredit.creditcat.util.GZIPUtils;
import com.vcredit.creditcat.vo.product.h5.CommonApiRequest;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;

@Service
public class CommonApiRequestService {

	// 合作方公钥
	@Value("${parent.publicKey}")
	private String publicKey;
	// 信用猫私钥
	@Value("${xinyongmao.privateKey}")
	private String privateKey;
	
	/**
	 * 统一包装请求
	 * @author zhaoqi01
	 * @param url
	 * @param paramJson
	 * @return
	 * @throws Exception 
	 */
	public String wrapRequest(String url, String paramJson, boolean compress) throws Exception {
		CommonApiRequest request = new CommonApiRequest().init();
		request.setBiz_data(paramJson);
		request.setIs_compress(compress ? 1 : 0);
		// 信用猫使用合作方平台的RSA公钥对业务参数进行RSA加密
		String compressBizData = request.getBiz_data();
		byte[] data = compressBizData.getBytes("UTF-8");
		byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
        String base64encodedData = Base64Utils.encode(encodedData);
		request.setBiz_data(base64encodedData);
        // 如果需要压缩,在加密完成后做业务数据压缩
        if(request.getIs_compress() == 1) {
            request.setBiz_data(Base64Utils.encode(GZIPUtils.compress(base64encodedData)));
        }
		// 使用信用猫自己的RSA私钥对所有参数进行签名
		String requsetJson = JacksonUtil.Obj2Json(request);
		byte[] requestData = requsetJson.getBytes("UTF-8");
		String sign = RSAUtils.sign(requestData, privateKey);
		request.setSign(sign);

		return HttpRequest.doJson(url, JacksonUtil.Obj2Json(request));
	}
}
